import {RootState,DataItem} from "../../utils/index"
import {Toast} from "react-vant"

const infoData:RootState = {
    data:[],
    children_data:[],
    copy_data :[],
    details_data:JSON.parse(window.localStorage.getItem("details_data") as string)||[],
    charts_data:{}
}

const reducer = (state = infoData,{type,payload}:any) =>{
    let newState = JSON.parse(JSON.stringify(state))
    switch (type) {
        case "GET_LIST":
            newState.data = payload
            newState.children_data = payload[0].children
            newState.copy_data = payload[0].children
            return newState 
        case "GET_CHAETS":
            newState.charts_data = payload

            return newState 

        case "CHECK_CHILDREN_DATA":
            newState.children_data = newState.data[payload].children
            newState.copy_data = newState.data[payload].children
            return newState 

        case "ADD_LIST":
            newState.children_data = [...newState.children_data,...payload]
            newState.copy_data = [...newState.children_data,...payload]
            return newState 

        // eslint-disable-next-line no-duplicate-case
        case "DELETE_SHOPCAR_DATA":
             newState.children_data.forEach((item:DataItem,index:number)=>{
                if (item.id === payload.id) {
                    newState.children_data.splice(index, 1)
                    Toast.success("删除成功")
                }
            })
            newState.copy_data = newState.children_data
            return newState 
        case "set_details_data":
                newState.details_data[0] = payload
                window.localStorage.setItem('details_data', JSON.stringify(newState.details_data))
            return newState 
        case "SEARCH_VALUE":
            newState.children_data = newState.copy_data.filter((item:DataItem)=>{
                return item.title.includes(payload) 
            })
            return newState 

            
        case "Like_DATA_COUNT":
            if (!payload.show_Like) {
                newState.details_data[0].like_count++
            }else{
                newState.details_data[0].like_count--
            }
            return newState

        case "FILTER_DATA":
            newState.children_data = newState.copy_data.filter((item:DataItem)=>{
                return item.type === payload
            })
            return newState 

        case "SORT_DATA":
            if (payload === "从低到高") {
                newState.children_data.sort((a:any,b:any)=>a.comments_count - b.comments_count)
            }else{
                newState.children_data.sort((a:any,b:any)=>b.comments_count - a.comments_count)
            }
            return newState 
            
        default:
            return newState 
    }
}

export default reducer